import { defineStore } from 'pinia'
import { reqLogin } from '@/api/user'
import type { loginParams } from '@/api/user/type'
import type { UserState } from './types/type'
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
import { constRoutes } from '@/router/routes'
import { reqUserInfo, reqCodeImage, reqLogout } from '@/api/user'

export const useUserStore = defineStore('user', {
  // 状态
  state: (): UserState => {
    return {
      token: GET_TOKEN(),
      menuRoutes: constRoutes, // 路由数组
      username: '',
      avatar: '',
    }
  },

  // 异步，执行逻辑的地方
  actions: {
    // 用户登陆
    async userLogin(data: loginParams) {
      const res = await reqLogin(data)
      // 登陆成功
      if (res.code === 200) {
        // pinaia存储token
        this.token = res.token as string
        // 本地存储持久化存储一份
        SET_TOKEN(res.token as string)
        // 返回成功
        return Promise.resolve(res.token)
      } else {
        // 登陆失败
        return Promise.reject(new Error(res.msg))
      }
    },

    // 获取用户信息
    async userInfo() {
      // 获取用户信息进行仓库存储
      let res = await reqUserInfo()
      // 获取用户信息成功,存储用户信息
      if (res.code === 200) {
        this.username = res.user?.userName as string
        this.avatar = res.user?.avatar as string
        return Promise.resolve(res)
      } else {
        // 获取用户信息失败
        return Promise.reject(new Error(res.msg))
      }
    },

    // 退出登陆
    async logout() {
      // 验证 token 格式
      if (this.token && !/^[\x00-\x7F]*$/.test(this.token as string)) {
        console.warn('Token contains invalid characters')
        // 清理无效 token
        this.token = ''
        REMOVE_TOKEN()
        return Promise.reject(new Error('Token 格式无效'))
      }

      let res = await reqLogout(this.token as string)
      if (res.code === 200) {
        // 退出登陆成功
        this.token = ''
        this.username = ''
        this.avatar = ''
        REMOVE_TOKEN()
        return Promise.resolve(res)
      } else {
        // 退出登陆失败
        return Promise.reject(new Error('退出登陆失败'))
      }
    },

    // 获取验证码
    async imageCode() {
      let res = await reqCodeImage()
      if (res.code === 200) {
        return Promise.resolve(res)
      } else {
        return Promise.reject(new Error(res.msg))
      }
    },
  },

  getters: {},
})
